import axios from 'axios';

//声明 reducer
let heroReducer = (state={
  heros: [],
  isFirst: true,
  loading: false
}, action) => {
  //根据 action 对 state 进行更新
  switch(action.type){
    //请求前类型
    case 'BEFORE_REQUEST':
      return {
        heros: [],
        loading: true,
        isFirst: false
      }
    
    //请求成功后  {type: 'SUCCESS_REQUEST', payload: [{id: 1}, {id: 2}]}
    case 'SUCCESS_REQUEST':
      return {
        heros: action.payload,
        loading: false,
        isFirst: false
      }
    default:
      return state;
  }
}

export default heroReducer;

//声明『异步的 action』 creator 『声明一个函数, 返回异步的 action 函数』
export function reqGetHeroAction(keyword){
  return async dispatch => {
    //发送请求之前, 分发同步任务 BEFORE_REQUEST
    dispatch({type: 'BEFORE_REQUEST'});
    //发送请求
    let result = await axios.get('http://api.xiaohigh.com/heros', {
      params: {
        //name_like 是接口查询英雄名称的参数
        name_like: keyword
      }
    });
    //如果发送成功, 同步更新 redux 中的状态
    dispatch({type: 'SUCCESS_REQUEST', payload: result.data});
  }
}
